package com.gxa.admin.recycling.controller;
import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.common.JsonResult;
import com.gxa.core.recycling.exception.BusinessException;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * @author R
 * @data 2021-10-21 15:21
 */
@RestController
@ControllerAdvice
@Log4j2
public class ExceptionController {

    /**
     * 本质上就是一个aop的通知，专门用于加强异常出现的时候的抛出通知
     * 当有异常发生，抛出通知介入到目标操作
     * 并把异常对象注入到参数Exception中
     */
    @ExceptionHandler(BusinessException.class)
    public Map businessHandler(BusinessException e)  {

        JsonResult jsonResult = new JsonResult();
        ExceptionCode exceptionCode = e.getExceptionCode();
        jsonResult.setCode(exceptionCode.getCode());
        jsonResult.setMsg(exceptionCode.getMessage());
        return jsonResult.getDataMap();

    }

    @ExceptionHandler(Exception.class)
    public Map exceptionHandler(Exception e)  {


        //分割线
        log.info("-----------------begin-----------------------");
        // 先记录异常对象的toString状态: 包括异常类型和异常原因
        log.error(e);
        // 再遍历栈中的异常轨迹: 采用遍历方式
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            log.info(stackTraceElement);
        }
        //分割线方便阅读
        log.info("-------------------end---------------------");

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode(ExceptionCode.SERVER_FAILED.getCode());
        jsonResult.setMsg(ExceptionCode.SERVER_FAILED.getMessage());
        return jsonResult.getDataMap();
    }
}




